#include "ThreadPool.h"

// 构造ThreadPool
ThreadPool::ThreadPool(EventLoop* mainEventLoop, int count) {
	_index = 0;
	_isStart = false;
	_mainEventLoop = mainEventLoop;
	_threadNum = count;
	_workerThreads.clear();
}

// 析构ThreadPool
ThreadPool::~ThreadPool() {
	for (auto item : _workerThreads) { delete item; }
}

// 启动线程池
void ThreadPool::run() {
	assert(!_isStart);

	// 1. 当前线程是主线程则正常，不是主线程则异常
	if (_mainEventLoop->getThreadID() != this_thread::get_id()) { exit(0); }

	// 2. 初始化并启动线程池中的每个线程
	_isStart = true;
	if (_threadNum > 0) {
		for (int i = 0; i < _threadNum; ++i) {
			WorkerThread* subThread = new WorkerThread(i);
			subThread->run();
			_workerThreads.push_back(subThread);
		}
	}
}

// 取出[线程池的某个子线程]的反应堆实例
EventLoop* ThreadPool::takeWorkerEventLoop() {
	assert(_isStart);
	// 1. 当前线程是主线程则正常，不是主线程则异常
	if (_mainEventLoop->getThreadID() != this_thread::get_id()) { exit(0); }

	// 2. 从线程池中找一个子线程，然后取出它的反应堆实例。若没有子线程，则返回主线程的反应堆
	EventLoop* evLoop = _mainEventLoop;
	if (_threadNum > 0) {
		evLoop = _workerThreads[_index]->getEventLoop();
		_index = (++_index) % _threadNum;
	}
	return evLoop;
}
